// pages/publish-records/publish-records.js
const app = getApp()

Page({
  data: {
    // 筛选类型
    filterTypes: [
      { label: '全部', value: 'all' },
      { label: '劳务', value: 'labor' }
    ],
    currentFilter: 'all', // 默认选择全部
    
    // 统计数据
    stats: {
      laborCount: 0,
      substituteCount: 0,
      errandCount: 0
    },
    
    // 发布记录列表
    publishRecords: [],
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 10
  },

  onLoad() {
    this.loadPublishRecords()
  },

  onShow() {
    // 每次显示时刷新数据
    this.setData({
      page: 1,
      publishRecords: [],
      hasMore: true
    })
    this.loadPublishRecords()
  },

  // 加载发布记录
  async loadPublishRecords() {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      if (!app.globalData.token) {
        wx.reLaunch({
          url: '/pages/login/login'
        })
        return
      }

      // 调用后端API获取发布记录
      const [statsResult, recordsResult] = await Promise.all([
        this.loadPublishStats(),
        this.loadPublishRecordsList()
      ])

      if (this.data.page === 1) {
        this.setData({
          publishRecords: recordsResult.records,
          stats: statsResult
        })
      } else {
        this.setData({
          publishRecords: [...this.data.publishRecords, ...recordsResult.records]
        })
      }

      // 设置分页信息
      this.setData({
        hasMore: this.data.page < recordsResult.pages,
        page: this.data.page + 1
      })

    } catch (error) {
      console.error('加载发布记录失败:', error)
      app.utils.showError('加载失败，请重试')
    } finally {
      this.setData({ loading: false })
    }
  },

  // 加载发布记录统计
  async loadPublishStats() {
    try {
      const result = await app.utils.request({
        url: '/publish-record/stats',
        method: 'GET'
      })

      if (result.code === 200) {
        return result.data
      } else {
        throw new Error(result.message || '获取统计信息失败')
      }
    } catch (error) {
      console.error('获取发布记录统计失败:', error)
      // 返回默认统计信息
      return {
        laborCount: 0,
        substituteCount: 0,
        errandCount: 0
      }
    }
  },

  // 加载发布记录列表
  async loadPublishRecordsList() {
    try {
      const requestData = {
        page: this.data.page,
        size: this.data.pageSize
      }
      
      // 只有当不是"全部"时才传递type参数
      if (this.data.currentFilter !== 'all') {
        requestData.type = this.data.currentFilter
      }
      
      const result = await app.utils.request({
        url: '/publish-record/list',
        method: 'GET',
        data: requestData
      })

      if (result.code === 200) {
        return result.data
      } else {
        throw new Error(result.message || '获取发布记录失败')
      }
    } catch (error) {
      console.error('获取发布记录列表失败:', error)
      // 返回空数据
      return {
        records: [],
        total: 0,
        pages: 0,
        current: this.data.page,
        size: this.data.pageSize
      }
    }
  },


  // 筛选条件改变
  onFilterChange(e) {
    const filterValue = e.currentTarget.dataset.value
    this.setData({
      currentFilter: filterValue,
      page: 1,
      publishRecords: [],
      hasMore: true
    })
    this.loadPublishRecords()
  },


  // 编辑劳务
  editLabor(e) {
    const id = e.currentTarget.dataset.id
    console.log('编辑劳务:', id)
    
    wx.navigateTo({
      url: `/pages/labor/edit/edit?laborId=${id}`
    })
  },

  // 阻止事件冒泡
  stopPropagation(e) {
    // 空函数，用于阻止事件冒泡
  },

  // 查看应聘者信息
  viewApplicants(e) {
    const laborId = e.currentTarget.dataset.id
    
    // 跳转到应聘者信息页面
    wx.navigateTo({
      url: `/pages/labor/applicants/applicants?laborId=${laborId}`
    })
  },

  // 查看发布记录详情
  viewRecordDetail(e) {
    const recordId = e.currentTarget.dataset.id
    const recordType = e.currentTarget.dataset.type
    
    // 根据记录类型跳转到对应的详情页面
    if (recordType === 'labor') {
      // 跳转到劳务详情页面
      wx.navigateTo({
        url: `/pages/labor/detail/detail?id=${recordId}`
      })
    } else if (recordType === 'errand') {
      // 跳转到跑腿详情页面
      wx.navigateTo({
        url: `/pages/errand/detail/detail?id=${recordId}`
      })
    } else if (recordType === 'express') {
      // 跳转到快递详情页面
      wx.navigateTo({
        url: `/pages/express/detail/detail?id=${recordId}`
      })
    } else if (recordType === 'substitute-class') {
      // 跳转到代课详情页面
      wx.navigateTo({
        url: `/pages/substitute-class/detail/detail?id=${recordId}`
      })
    } else {
      // 默认跳转到劳务详情页面
      wx.navigateTo({
        url: `/pages/labor/detail/detail?id=${recordId}`
      })
    }
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡，防止点击按钮时触发记录详情跳转
  },

  // 取消劳务
  async cancelLabor(e) {
    const laborId = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个劳务吗？取消后无法恢复。',
      confirmText: '确定取消',
      confirmColor: '#dc2626',
      success: async (res) => {
        if (res.confirm) {
          try {
            app.utils.showLoading('正在取消...')
            
            const result = await app.utils.request({
              url: `/publish-record/cancel/${laborId}`,
              method: 'POST'
            })

            if (result.code === 200) {
              app.utils.showSuccess('劳务已取消')
              // 刷新列表
              this.setData({
                page: 1,
                publishRecords: [],
                hasMore: true
              })
              this.loadPublishRecords()
            } else {
              throw new Error(result.message || '取消失败')
            }
          } catch (error) {
            console.error('取消劳务失败:', error)
            app.utils.showError('取消失败，请重试')
          } finally {
            app.utils.hideLoading()
          }
        }
      }
    })
  },

  // 完成劳务
  async completeLabor(e) {
    const laborId = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '标记完成',
      content: '确定要标记这个劳务为已完成吗？标记后表示任务已经完成。',
      confirmText: '确定完成',
      confirmColor: '#16a34a',
      success: async (res) => {
        if (res.confirm) {
          try {
            app.utils.showLoading('正在标记完成...')
            
            const result = await app.utils.request({
              url: `/publish-record/complete/${laborId}`,
              method: 'POST'
            })

            if (result.code === 200) {
              app.utils.showSuccess('劳务已标记为完成')
              // 刷新列表
              this.setData({
                page: 1,
                publishRecords: [],
                hasMore: true
              })
              this.loadPublishRecords()
            } else {
              throw new Error(result.message || '操作失败')
            }
          } catch (error) {
            console.error('完成劳务失败:', error)
            app.utils.showError('操作失败，请重试')
          } finally {
            app.utils.hideLoading()
          }
        }
      }
    })
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadPublishRecords()
    }
  },

  // 去发布页面
  goToPublish() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      publishRecords: [],
      hasMore: true
    })
    this.loadPublishRecords().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadMore()
  }
})
